import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from modules.yolov3.yololayer import YoloLayer
from torchvision.models import resnet

# <function make_conv2d_bn_leaky/>
def make_conv2d_bn_leaky(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros'):
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, False, padding_mode),
        nn.BatchNorm2d(out_channels, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True),
        nn.LeakyReLU()
    )
# </function make_conv2d_bn_leaky>

# <function conv3x3/>
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
# </function conv3x3>

# <function conv1x1/>
def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
# </function conv1x1>

# <class BasicBlock(nn.Module)/>
class BasicBlock(nn.Module):
    expansion = 1
    # </method __init__>
    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None):
        super(BasicBlock, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        if groups != 1 or base_width != 64:
            raise ValueError('BasicBlock only supports groups=1 and base_width=64')
        if dilation > 1:
            raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm_layer(planes)
        self.relu = nn.LeakyReLU(inplace=True) # nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm_layer(planes)
        self.downsample = downsample
        self.stride = stride
    # </method __init__>

    # </method forward>
    def forward(self, x):
        identity = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        if self.downsample is not None:
            identity = self.downsample(x)
        out += identity
        out = self.relu(out)
        return out
    # </method forward>
# </class BasicBlock(nn.Module)>

# <class Bottleneck(nn.Module)/>
class Bottleneck(nn.Module):
    expansion = 4
    # <method __init__/>
    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                 base_width=64, dilation=1, norm_layer=None):
        super(Bottleneck, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        width = int(planes * (base_width / 64.)) * groups
        # Both self.conv2 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv1x1(inplanes, width)
        self.bn1 = norm_layer(width)
        self.conv2 = conv3x3(width, width, stride, groups, dilation)
        self.bn2 = norm_layer(width)
        self.conv3 = conv1x1(width, planes * self.expansion)
        self.bn3 = norm_layer(planes * self.expansion)
        self.relu = nn.LeakyReLU(inplace=True) # nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride
    # </method __init__>

    # <method forward/>
    def forward(self, x):
        identity = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)
        out = self.conv3(out)
        out = self.bn3(out)
        if self.downsample is not None:
            identity = self.downsample(x)
        out += identity
        out = self.relu(out)
        return out
    # </method forward>
# </class Bottleneck(nn.Module)>

# <class ResNetFeature(nn.Module)/>
class ResNetFeature(nn.Module):
    """
    ResNetFeature. Data: 2019-09-23 11:30
    """
    # <method __init__/>
    def __init__(self, block, layers, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
        super(ResNetFeature, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer
        self._inplanes = 64
        self._dilation = 1
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None or a 3-element tuple, got {}".format(replace_stride_with_dilation))
        self._groups = groups
        self.base_width = width_per_group
        self.conv1 = nn.Conv2d(3, self._inplanes, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = norm_layer(self._inplanes)
        self.relu = nn.LeakyReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2])
    # </method __init__>
    
    # <method _make_layer/>
    def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
        norm_layer = self._norm_layer
        downsample = None
        previous_dilation = self._dilation
        if dilate:
            self._dilation *= stride
            stride = 1
        # end-if
        if stride != 1 or self._inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self._inplanes, planes * block.expansion, stride),
                norm_layer(planes * block.expansion),
                )
        # end-if
        layers = []
        layers.append(block(self._inplanes, planes, stride, downsample, self._groups, self.base_width, previous_dilation, norm_layer))
        self._inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self._inplanes, planes, groups=self._groups, base_width=self.base_width, dilation=self._dilation, norm_layer=norm_layer))
        # end-for
        return nn.Sequential(*layers)
    # </method _make_layer>

    # <method forward/>
    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)
        output_fms = []
        x = self.layer1(x)
        output_fms.append(x)
        x = self.layer2(x)
        output_fms.append(x)
        x = self.layer3(x)
        output_fms.append(x)
        x = self.layer4(x)
        output_fms.append(x)
        return output_fms
    # </method forward>
# </class ResNetFeature(nn.Module)>

# <function make_resnet_feature/>
def make_resnet_feature(name = "resnet18", **kwargs):
    if name == "resnet18":
        return ResNetFeature(BasicBlock, [2, 2, 2, 2], **kwargs)
    elif name == "resnet34":
        return ResNetFeature(BasicBlock, [3, 4, 6, 3], **kwargs)
    elif name == "resnet50":
        return ResNetFeature(Bottleneck, [3, 4, 6, 3], **kwargs)
    elif name == "resnet101":
        return ResNetFeature(Bottleneck, [3, 4, 23, 3], **kwargs)
    elif name == "resnet152":
        return ResNetFeature(Bottleneck, [3, 8, 36, 3], **kwargs)
    elif name == "resnext50_32x4d":
        kwargs['groups'] = 32
        kwargs['width_per_group'] = 4
        return ResNetFeature(Bottleneck, [3, 4, 6, 3], **kwargs)
    elif name == "resnext101_32x8d":
        kwargs['groups'] = 32
        kwargs['width_per_group'] = 8
        return ResNetFeature(Bottleneck, [3, 4, 23, 3], **kwargs)
    else:
        raise RuntimeError("""Unknow ResNet Name: {}""".format(name))
    # end-if
    return None
# </function make_resnet_feature>

# <class FDNet(nn.Module)/>
class FDNet(nn.Module):
    """Some Information about FDNet. Data: 2019-09-23 11:30 """
    # <method __init__/>
    def __init__(
        self, 
        grids,
        anchors,
        num_classes,
        img_size,
        ):
        super(FDNet, self).__init__()
        self._feature = make_resnet_feature("resnet18")
        inp = torch.rand(1, 3, 416, 416)
        outps = self._feature(inp)
        ocs = [outp.size(1) for outp in outps]
        # 
        self._yolo_layers = []
        for idx in range(len(anchors)):
            self._yolo_layers.append( YoloLayer(anchors = anchors[idx], num_classes = num_classes, image_size = img_size) )
        # end-for
        # group 0 ...
        in_plane_0 = 16
        self._conv_sets_0 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=ocs[-1], out_channels=in_plane_0, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_0, out_channels=in_plane_0*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_0*2, out_channels=in_plane_0, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_0, out_channels=in_plane_0*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_0*2, out_channels=in_plane_0, kernel_size=1, stride=1, padding=0, dilation=1, groups=1)
            )
        self._conv_before_yolo_0 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=in_plane_0, out_channels=in_plane_0*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            nn.Conv2d(in_channels=in_plane_0*2, out_channels=len(anchors[0])*(5+num_classes), kernel_size=1, stride=1, padding=0, dilation=1, groups=1)
            )
        self._conv_up_0 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=in_plane_0, out_channels=in_plane_0*2, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            nn.UpsamplingNearest2d(scale_factor=2)
            )
        # group 1 ...
        in_plane_1 = 16
        self._conv_sets_1 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=ocs[-2] + in_plane_0 * 2, out_channels=in_plane_1, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_1, out_channels=in_plane_1*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_1*2, out_channels=in_plane_1, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_1, out_channels=in_plane_1*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_1*2, out_channels=in_plane_1, kernel_size=1, stride=1, padding=0, dilation=1, groups=1)
            )
        self._conv_before_yolo_1 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=in_plane_1, out_channels=in_plane_1*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            nn.Conv2d(in_channels=in_plane_1*2, out_channels=len(anchors[1])*(5+num_classes), kernel_size=1, stride=1, padding=0, dilation=1, groups=1)
            )
        self._conv_up_1 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=in_plane_1, out_channels=in_plane_1*2, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            nn.UpsamplingNearest2d(scale_factor=2)
            )
        # gourp 2 ...
        in_plane_2 = 16
        self._conv_sets_2 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=ocs[-3] + in_plane_1 * 2, out_channels=in_plane_2, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_2, out_channels=in_plane_2*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_2*2, out_channels=in_plane_2, kernel_size=1, stride=1, padding=0, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_2, out_channels=in_plane_2*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            make_conv2d_bn_leaky(in_channels=in_plane_2*2, out_channels=in_plane_2, kernel_size=1, stride=1, padding=0, dilation=1, groups=1)
            )
        self._conv_before_yolo_2 = nn.Sequential(
            make_conv2d_bn_leaky(in_channels=in_plane_2, out_channels=in_plane_2*2, kernel_size=3, stride=1, padding=1, dilation=1, groups=1),
            nn.Conv2d(in_channels=in_plane_2*2, out_channels=len(anchors[2])*(5+num_classes), kernel_size=1, stride=1, padding=0, dilation=1, groups=1)
            )
        # initialize params ...
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            # end-if
        # end-for
        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        zero_init_residual = True
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)
                elif isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)        
                # end-if
            # end-for
        # end-if
    # </method __init__>

    # <method forward/>
    def forward(self, x):
        nI_h = x.size(2)
        nI_w = x.size(3)
        features = self._feature(x)
        # parse the features ...
        features_before_yolo = []
        # group 0 ...
        inp_g0 = features[-1]
        out_conv_sets_0 = self._conv_sets_0(inp_g0)
        features_before_yolo.append(self._conv_before_yolo_0(out_conv_sets_0))
        out_conv_up_0 = self._conv_up_0(out_conv_sets_0)
        # group 1 ...
        inp_g1 = torch.cat((features[-2], out_conv_up_0), 1)
        out_conv_sets_1 = self._conv_sets_1(inp_g1)
        features_before_yolo.append(self._conv_before_yolo_1(out_conv_sets_1))
        out_conv_up_1 = self._conv_up_1(out_conv_sets_1) 
        # group 2 ...
        inp_g2 = torch.cat((features[-3], out_conv_up_1), 1)
        out_conv_sets_2 = self._conv_sets_2(inp_g2)
        features_before_yolo.append(self._conv_before_yolo_2(out_conv_sets_2))
        # forward yolo layer ...
        encoded_fms = [ ]
        decoded_fms = [ ]
        for idx in range(len(features_before_yolo)):
            encoded_fm, decode_fm = self._yolo_layers[idx](features_before_yolo[idx], nI_h, nI_w)
            encoded_fms.append(encoded_fm)
            decoded_fms.append(decode_fm)
        # end-for
        return torch.cat(encoded_fms, 1), torch.cat(decoded_fms, 1)
    # </method forward>
# </class FDNet(nn.Module)>

if __name__ == "__main__":
    import sys 
    sys.path.append('../ModelCompression')
    from graph import reconstructor
    from utils.compressmethod import showFMLAs
    
    grids = [[13,13],[26,26],[52,52]]
    anchors = [[[116,90],[156,198],[373,326]],[[30,61],[62,45],[59,119]],[[10,13],[16,30],[33,23]]]
    num_classes = 2
    inp = torch.rand(1, 3, 416, 416)        
    net = FDNet(grids, anchors, num_classes, (416,416))
    outp = net(inp)
    
    fmlas_origin = showFMLAs(inp, net)
    print("""FMLAs: {} M""".format(fmlas_origin / 1e6))
    reconstructor.insertCaptureBoundaryStart(net)
    output = net(inp)
    reconstructor.insertCaptureBoundaryEnd()
    origin_net, graph = reconstructor.getReconstructedNetwork(ifDraw=True, drawPath="./modules/net.png")